package com.example.advancecomponents.adaptors;

import static android.content.Context.MODE_PRIVATE;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.example.advancecomponents.MainActivity;
import com.example.advancecomponents.R;
import com.example.advancecomponents.vo.Star;

import java.util.List;

public class SimpleImageViewPagerAdapter extends PagerAdapter {
    private final Context context;
    protected final List<Star> stars;

    public SimpleImageViewPagerAdapter(Context context, List<Star> stars) {

        this.context = context;
        this.stars = stars;

    }

    @Override
    public int getCount() {
        return stars.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {

        Star star = stars.get(position);


        View view = LayoutInflater.from(context).inflate(R.layout.star_page_pager, null);

        View goToButton = view.findViewById(R.id.goTo);


        if (position == stars.size() - 1) {
            // 到达最后一页，设置点击跳转事件
            goToButton.setOnClickListener(v -> {

                // 标记已经不是首次启动
                context.getSharedPreferences("config", MODE_PRIVATE).edit()
                        .putBoolean("firstBoot", false)
                        .apply();

                Intent intent = new Intent(context, MainActivity.class);

                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            });
        } else {
            // 不是最后一页，跳转按钮不可见
            goToButton.setVisibility(View.GONE);
        }

        ImageView img = view.findViewById(R.id.img);
        img.setImageResource(star.getIcon());

        TextView description = view.findViewById(R.id.detailDescription);
        description.setText(star.getDetail());

        container.addView(view);

        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }
}
